import java.util.*;
import java.lang.Exception;

class SelectionList {
	private LinkedList<CommEvent> selectionList;
	
	public SelectionList() {
		selectionList = new LinkedList<CommEvent>();
	}
	
	public void AddEvent(CommEvent ce) {
		synchronized (Lock.lock) {
			selectionList.add(ce);
		}
	}
	
	public CommEvent Select() throws InterruptedException {
		synchronized (Lock.lock) {
			// First call Poll() to see if any of the CommEvents are
			// already ready
			for (int i = 0; i < selectionList.size(); ++i) {
				if (selectionList.get(i).Poll()) {
					return selectionList.remove(i);
				}
			}
			
			// If we get here, no CommEvents were ready so Enqueue them
			for (int i = 0; i < selectionList.size(); ++i) {
				selectionList.get(i).Enqueue();
			}
			
			// Wait until one of the communications has occurred
			CommEvent event = null;
			while (event == null) {
				Lock.lock.wait();
				for (int i = 0; i < selectionList.size(); ++i) {
					if (selectionList.get(i).CommOccurred()) {
						event = selectionList.remove(i);
						break;
					}
				}
			}
			
			// Remove everybody else from their queues
			for (int i = 0; i < selectionList.size(); ++i) {
				selectionList.get(i).Dequeue();
			}
			
			Lock.lock.notifyAll();
			return event;
		}
	}
}
